from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import redis_store
from info.constants import CLICK_RANK_MAX_NEWS
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


@index_blu.route('/')
@user_login_data
def index():
    """
    如果用户登陆，将当前登陆用户的数据传到模板中，让模板显示
    :return:
    """
    # 显示用户是否登陆逻辑
    # user_id = session.get("user_id", None)
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user

    new_list = []
    try:
        new_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 将从数据库中取出的模型对象new_list转换乘json格式(字典形式)，使用到to_basic_dict()函数
    new_dict_li = []
    for news in new_list:
        new_dict_li.append(news.to_basic_dict())

    categories = Category.query.all()
    category_li = []

    for category in categories:
        category_li.append(category.to_dict())

    data = {
        "user":user.to_dict() if user else None,
        "new_dict_li":new_dict_li,
        "category_li":category_li
    }

    return render_template('news/index.html', data=data)


@index_blu.route('/news_list')
def news_list():

    # 获取首页新闻数据

    # １．获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # ２．校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    filters = []
    if cid != 1:
        # 添加条件
        filters.append(News.category_id == cid)

    # ３．查询数据
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    # 取到当前页的数据
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_dict_li":news_dict_li
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)

@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')